#!/usr/bin/env node
const { execSync, spawnSync } = require('child_process');
const fs = require('fs');
const path = require('path');

function commandExists(cmd) {
    try {
        const result = spawnSync(cmd, ['--version'], { stdio: 'ignore', shell: true });
        return result.status === 0;
    } catch {
        return false;
    }
}

async function main() {
    const args = process.argv.slice(2);
    const projectName = args[0];

    if (!projectName) {
        console.error('请指定项目名，示例：init-project my-app');
        process.exit(1);
    }

    const repoUrl = 'http://121.40.229.168:7002/frontgroup/sh-demo/'; // 你公司模板仓库地址
    const targetDir = path.resolve(process.cwd(), projectName);

    if (fs.existsSync(targetDir)) {
        console.error(`目录 ${projectName} 已存在，请换一个项目名`);
        process.exit(1);
    }

    console.log(`开始克隆模板仓库到目录 ${projectName} ...`);
    execSync(`git clone --branch master --single-branch ${repoUrl} ${projectName}`, { stdio: 'inherit' });

    const gitDir = path.join(targetDir, '.git');
    if (fs.existsSync(gitDir)) {
        if (process.platform === 'win32') {
            execSync(`rmdir /s /q "${gitDir}"`, { stdio: 'inherit' });
        } else {
            execSync(`rm -rf "${gitDir}"`, { stdio: 'inherit' });
        }
    }

    const pkgPath = path.join(targetDir, 'package.json');
    if (fs.existsSync(pkgPath)) {
        const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
        pkg.name = projectName;
        fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2), 'utf-8');
        console.log('已更新 package.json 中的项目名称');
    } else {
        console.warn('package.json 未找到，跳过项目名替换');
    }

    const useCnpm = commandExists('cnpm');
    console.log(`开始安装依赖，使用的是 ${useCnpm ? 'cnpm' : 'npm'} ...`);
    execSync(`${useCnpm ? 'cnpm' : 'npm'} install`, { cwd: targetDir, stdio: 'inherit' });

    console.log('项目初始化完成！');
    console.log(`  cd ${projectName}`);
    console.log('  npm run dev');
}

main();
